package cn.edu.sdjzu.xg.eagle.dao;

import cn.edu.sdjzu.xg.eagle.Service.CommonDaoService;
import cn.edu.sdjzu.xg.eagle.entity.Condition;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


/**
 *  通用数据访问工具类
 *  提供数据表的 记录数统计 功能
 *  支持 无条件统计 和 带条件统计
 */
public class CommonDao implements CommonDaoService {

    //  单例模式设计
    private static CommonDao commonDao = new CommonDao();

    private CommonDao() {}

    //  获取 CommonDao 的唯一实例
    public static CommonDao getInstance() {
        return commonDao;
    }

    /**
     * 统计指定表的总记录数（无条件）
     * @param connection 数据库连接对象
     * @param tableName 表名
     * @return 表中的记录总数
     * @throws SQLException 如果发生 SQL 异常
     */

    //  无条件的总记录数
    public int countAll(Connection connection,String tableName) throws SQLException {
        //  sql语句
        String sql = "SELECT COUNT(id) as cnt FROM "+tableName;
        //预编译
        PreparedStatement pstmt = connection.prepareStatement(sql);
        //
        ResultSet rs = pstmt.executeQuery();
        //统计变量
        int count = 0;
        //
        if(rs.next()) {
            count = rs.getInt("cnt");
        }
        JdbcHelper.close(rs, pstmt);
        return count;
    }

    //  带条件的记录数
    public int count(Connection connection, String tableName, List<Condition> conditionList) throws SQLException {
        StringBuilder sql = new StringBuilder("SELECT COUNT(id) as cnt FROM " + tableName);
        if (conditionList != null && !conditionList.isEmpty()) {
            String whereClause = Condition.toWhereClause(conditionList);
            if (!whereClause.isEmpty()) {
                sql.append(" ").append(whereClause);
            }
        }
        PreparedStatement pstmt = connection.prepareStatement(sql.toString());
        ResultSet rs = pstmt.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt("cnt");
        }
        JdbcHelper.close(rs, pstmt);
        return count;
    }
}
